import { Link, useNavigate } from "react-router-dom";
import React, { useState } from "react";
import Bottom from "../components/bottom/Bottom";
import { Top } from "../components/top/Top";
import "./Login.css"; // 样式自定义
import { accountService } from "../../service/accountService";
import { common_utils } from "../../utils/utils";

export default function Login() {
  return (
    <>
      <Top />
      <div className="container">
        <div className="login-form-box">
          <LoginForm />
          <div className="register-link">
            Need a user name and password?{" "}
            <Link to="/register">Register Now!</Link>
          </div>
        </div>
      </div>
      <Bottom />
    </>
  );
}

function LoginForm() {
  const [signOnMsg, setSignOnMsg] = useState(null);
  const [formData, setFormData] = useState({ username: "", password: "" });

  // 处理输入变化
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    accountService.login(formData.username, formData.password, (response) => {
      console.log(response);
      if (response.msg === "用户名不存在") {
        setSignOnMsg("用户名不存在");
      } else if (response.msg === "密码错误") {
        setSignOnMsg("密码错误");
      } else {
        const { username, image } = response.data.account;
        const user = {
          username: username,
          image: image,
        };
        localStorage.setItem("user", JSON.stringify(user));
        localStorage.setItem("token", response.data.token);
        common_utils.toMain();
      }
    });
  };

  return (
    <form onSubmit={handleSubmit} className="login-form">
      <h2>Login</h2>
      {signOnMsg && (
        <p className="login-error" style={{ color: "red" }}>
          {signOnMsg}
        </p>
      )}
      <div className="form-group">
        <label>Username:</label>
        <input
          type="text"
          name="username"
          value={formData.username}
          onChange={handleChange} // 添加 onChange 事件
          required
        />
      </div>
      <div className="form-group">
        <label>Password:</label>
        <input
          type="password"
          name="password"
          value={formData.password}
          onChange={handleChange} // 添加 onChange 事件
          required
        />
      </div>
      <input type="submit" value="Login" className="login-btn" />
    </form>
  );
}